// pages/orderDetail/orderDetail.js
var util = require('../../utils/util.js')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    //用于存储[订单详情]数据
    //orderDetail: undefined ,设置为undefined会导致二次渲染，画面有过渡
    status: ['已完成', '进行中'],
    newStatus: '' // 用来存储变更状态时候的新状态,不与视图层交互
  },

  //------------------------------当点击的商品拥有折叠价格明细时，展开
  openDetailPriceClick: function (e) {
    let options = e.currentTarget.dataset.options; //加料描述
    let folded = e.currentTarget.dataset.folded; //折叠属性
    let id = e.currentTarget.dataset.id; //当前产品数据id

    if (options == '') {
      //如果没有小料，直接退出
      return;
    }
    let cartListData = this.data.orderDetail.cartListData;
    if (cartListData[id].folded == true || cartListData[id].folded == "true") {
      cartListData[id].folded = false;
    }
    else if (cartListData[id].folded == false || cartListData[id].folded == "false") {
      cartListData[id].folded = true;
    }
    else {
      cartListData[id].folded = false;
    }

    this.setData({
      'orderDetail.cartListData': cartListData
    })
  },
  //------------------------------若当前用户为【管理员】，则可以修改订单状态
  changeOrderStatus: function (e) {
    let that = this;
    let status = this.data.status;
    let userInfo = wx.getStorageSync('userInfo')
    if (userInfo.role != '管理员') {
      //非管理员权限禁止变更状态
      return;
    }
    //剔除数组中的当前状态
    for (let i = 0; i < status.length; i++) {
      if (status[i] == that.data.orderDetail.status) {
        status.splice(i, 1);
        break;
      }
    }
    wx.showActionSheet({
      itemList: status,
      itemColor: '#3CC51F',
      success: function (res) {
        let newStatus = status[res.tapIndex];
        //将管理员变更的订单状态记录至内存中的【newStatus】
        that.data.newStatus = newStatus;
        let orderId = that.data.orderDetail.orderId;
        console.log(orderId)
        //调用云函数变更数据库中的订单状态
        wx.cloud.callFunction({
          name: 'changeOrderStatus',
          data: {
            newStatus: newStatus, //新状态  
            orderId: orderId//订单id
          }
        })
          .then(res => {
            if (res.result.result == 'success') {
              wx.navigateBack({
                delta: 1
              })
              //向用户发送变更状态通知
              that.sendMessageToUsers();
            }
            else {
              wx.showModal({
                title: '管理员注意',
                content: '变更状态失败(error:' + res.result.error + ')',
                showCancel: false
              })
            }
          })
      },
      fail: function (res) {
        //用户进行了取消操作，啥也不需要干
        console.log(res.errMsg)
      }
    })
  },
  //------------------------------【发送模板消息】，向用户发送订单状态变更通知
  sendMessageToUsers: function () {
    let that = this;
    let orderDetail = this.data.orderDetail //获取当前页面的订单详情
    let now = this.getNowDate();
    let orderDescrib = '';
    //根据orderDetail中的的cartListData获取订单详情
    for (let i = 0; i < orderDetail.cartListData.length; i++) {
      orderDescrib += '名称:' + orderDetail.cartListData[i].name + '  加料:' + (orderDetail.cartListData[i].options == '' ? '无' : orderDetail.cartListData[i].options) + '  数量:' + orderDetail.cartListData[i].count + '\n'
    }
    let sendData = {
      touser: orderDetail.openId, //接收人openid
      template_id: 'PCSK6rRY8bZymYrljwF3vdlGhx9o9uxlz4HQC6KYnRo', //模板消息id
      page: "pages/index/index",
      form_id: orderDetail.prepayId,
      data: {
        keyword1: {
          value: that.data.newStatus //订单状态
        },
        keyword2: {
          value: orderDetail.orderId  //订单号
        },
        keyword3: {
          value: now //变更时间
        },
        keyword4: {
          value: orderDetail.orderTypeName //订单类型
        },
        keyword5: {
          value: orderDetail.simpleId//兑换码

        },
        keyword6: {
          value: '￥' + orderDetail.totalCost  //订单金额
        },
        keyword7: {
          value: orderDescrib //订单详情
        },
        keyword8: {
          value: orderDetail.orderRemark //订单备注
        }
      },
      emphasis_keyword: "keyword1.DATA"
    };
    console.log(sendData);
    util.sendTemplate(sendData);
  },
  //-------------------------------------------------拨打当前快递电话
  callPhone: function (e) {
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.phone,
    })
  },
  //-------------------------------------------------打开当前位置
  openCurrentPosition: function () {
    let addrInfo = this.data.orderDetail.address
    try {
      wx.showLoading({
        title: '正在定位',
      })
      wx.openLocation({
        latitude: Number(addrInfo.latitude),
        longitude: Number(addrInfo.longitude),
        scale: 18,
        name: addrInfo.address.split(' ')[1],
        address: addrInfo.address.split(' ')[0]
      })
      wx.hideLoading();
    }
    catch (e) {
      wx.showToast({
        title: '无法定位，请手动导航',
        icon: 'none'
      })
    }

  },
  //-------------------------------------------------获取当前时间
  getNowDate: function () {
    var date = new Date();
    var sign1 = "-";
    var sign2 = ":";
    var year = date.getFullYear() // 年
    var month = date.getMonth() + 1; // 月
    var day = date.getDate(); // 日
    var hour = date.getHours(); // 时
    var minutes = date.getMinutes(); // 分
    var seconds = date.getSeconds() //秒
    var weekArr = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期天'];
    var week = weekArr[date.getDay()];
    // 给一位数数据前面加 “0”
    if (month >= 1 && month <= 9) {
      month = "0" + month;
    }
    if (day >= 0 && day <= 9) {
      day = "0" + day;
    }
    if (hour >= 0 && hour <= 9) {
      hour = "0" + hour;
    }
    if (minutes >= 0 && minutes <= 9) {
      minutes = "0" + minutes;
    }
    if (seconds >= 0 && seconds <= 9) {
      seconds = "0" + seconds;
    }
    var currentdate = year + sign1 + month + sign1 + day + " " + hour + sign2 + minutes + sign2 + seconds + " " + week;
    return currentdate;
  },
  //-------------------------------------------------长按复制配送信息
  copyDeliverAddress:function(){
    let addr = this.data.orderDetail.address
    let addr_data = addr.address + '\n' + addr.addNumber + '\n' 
    + addr.name + '(' + addr.sex + ')' +'\n'+ addr.phone
    wx.setClipboardData({
      data: addr_data,
      success(res) {
        wx.showToast({
          title: '地址已复制',
          icon: 'none'
        })
      }
    })

  },
  //-------------------------------------------------长按复制备注信息
  copyRemark: function () {
    let remark = this.data.orderDetail.orderRemark
    wx.setClipboardData({
      data: remark,
      success(res) {
        wx.showToast({
          title: '备注已复制',
          icon: 'none'
        })
      }
    })

  },
  //-------------------------------------------------复制用户id至粘贴板
  copyUserId: function (e) {
    wx.setClipboardData({
      data: e.currentTarget.dataset.userid,
      success(res) {
          wx.showToast({
            title: '已复制',
            icon:'none'
          })
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //以下为orderDetail的测试数据
    // let orderDetail =
    // {
    //     "orderId": "FML153727652977759486931",
    //     "prepayId": "wx18211530413616c6aecf003b0196200630",
    //     "userId": "ID153680988219008521",
    //     "openId": "oy_8M5CuX-vsDNjj8AWivkfvs0Qo",
    //     "oneDayId": 1,
    //     "simpleId": "0001",
    //     "orderDate": "2018-09-18",
    //     "orderTime": "21:15:47",
    //     "orderTypeId": 3,
    //     "orderTypeName": "外卖配送",
    //     "reserveTime": "稍后",
    //     "address": {
    //       "name": "时宝顺",
    //       "sex": "先生",
    //       "phone": "15554795855",
    //       "addNumber": "123",
    //       "label": "家",
    //       "distance": "975",
    //       "address": "山东省济宁市微山县奎文路38号 微山县政府"
    //     },
    //     "orderRemark": "",
    //     "totalCount": 2,
    //     "totalCost": 2.2,
    //     "status": "进行中",
    //     "cartListData": [
    //       {
    //         "key": "价格测试(西瓜)",
    //         "name": "价格测试",
    //         "options": "西瓜",
    //         "nakedPrice": "0.1",
    //         "price": 2.1,
    //         "discount": 0.1,
    //         "count": 1,
    //         "additions": [
    //           {
    //             "addName": "西瓜",
    //             "addPrice": 2
    //           }
    //         ],
    //         "folded": true
    //       },
    //       {
    //         "key": "价格测试()",
    //         "name": "价格测试",
    //         "options": "",
    //         "nakedPrice": "0.1",
    //         "price": 0.1,
    //         "discount": 0,
    //         "count": 1,
    //         "additions": [
    //           {
    //             "addName": "西瓜",
    //             "addPrice": 2
    //           }
    //         ],
    //         "folded": true
    //       }
    //     ]
    // }
    let orderDetail = getApp().globalData.orderDetail;
    this.setData({
      orderDetail: orderDetail
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})